module("ProgressBar", package.seeall)

local ProgressBar = class("ProgressBar")

ProgressBar = class("ProgressBar",
        function ()
            return cc.Sprite:create()
        end)

ProgressBar.__index = ProgressBar

function create()
    local bar = ProgressBar.new()

    bar.min = 0
    bar.max = 100

    bar.hpAction = nil
    bar.hpBgAction = nil

    bar.bgSprite = cc.Sprite:create("res/hpBarBg.png")
    bar.colorBgSprite = cc.Sprite:create("res/hpBarColorBg.png")
    bar.colorSprite = cc.Sprite:create("res/hpBarColor.png")
    
    bar:setCascadeOpacityEnabled(true)

--    bar.bgSprite:setCascadeOpacityEnabled(true)
--    bar.colorSprite:setCascadeOpacityEnabled(true)
--    bar.colorBgSprite:setCascadeOpacityEnabled(true)
    
    bar.bgSprite:setAnchorPoint(0, 0.5)
    bar.colorSprite:setAnchorPoint(0, 0.5)
    bar.colorBgSprite:setAnchorPoint(0, 0.5)
    
    bar.colorSprite:setColor(cc.c3b(0, 255, 0))
    
    if (not bar.colorBgSprite) then
        print("create failed")
    end
    
    local size = bar.bgSprite:getContentSize()
    bar.bgSprite:setPosition(-size.width * 0.5, 0);
    bar.colorBgSprite:setPosition(-size.width * 0.5, 0);
    bar.colorSprite:setPosition(-size.width * 0.5, 0);
    
    bar:addChild(bar.bgSprite)
    bar:addChild(bar.colorBgSprite)
    bar:addChild(bar.colorSprite)
    
    return bar
end

function ProgressBar:setMin(min)
    self.min = min
end

function ProgressBar:setMax(max)
    self.max = max
end

function ProgressBar:setValue(value, animateHpTime, animateHpBgTime)

    local scaleX = value * 1.0 / (self.max - self.min)

    if (animateHpTime > 0) then
        self.hpAction = self.colorSprite:runAction(cc.ScaleTo:create(animateHpTime, scaleX, 1))
    else
        print(self.colorSprite)
        self.colorSprite:setScaleX(scaleX)
        local redParam = 255 * (1 - scaleX)
        local greenParam = 255 * scaleX
        self.colorSprite:setColor(cc.c3b(redParam, greenParam, 0))
    end
    
    if (animateHpBgTime > 0) then
        self.hpBgAction = self.colorBgSprite:runAction(cc.ScaleTo:create(animateHpBgTime, scaleX, 1))
    else
        self.colorBgSprite:setScaleX(scaleX)
    end

end
